package com.easypay.reactive8583.netty.codec;

import com.easypay.reactive8583.iso.MessageFactory;
import com.solab.iso8583.IsoMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.bytes.ByteArrayDecoder;

import java.text.ParseException;
import java.util.List;

/**
 * @author pandans
 * @date 2021/03/04 16:17
 * @Description:
 */
public class Iso8583Decoder extends ByteArrayDecoder {
    private MessageFactory<IsoMessage> messageMessageFactory;

    public Iso8583Decoder(MessageFactory<IsoMessage> messageMessageFactory) {
        this.messageMessageFactory = messageMessageFactory;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (!byteBuf.isReadable()) {
            return;
        }
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        IsoMessage isoMessage = this.messageMessageFactory.parseMessage(bytes, 0);
        if (isoMessage != null) {
            out.add(isoMessage);
        } else {
            throw new ParseException("Can't parse ISO8583 message", 0);
        }
    }
}
